import sdk from '../index';
import { analysisIntent } from "../tool/baseScene";
import { mathType } from "../tool/face";
import SkillManager from "./skill/SkManager";
import type { Skill } from "./types";
import { Attribute_base, 道具枚举 } from "../../shared/face/enums";
import gameCfg from "../../gameCfg";
import rpg_component from "../../component/rpg_component";
import { ComType } from "../tool/component";
import base_component from "../../component/base_component";
import talent_component from "../../component/talent_component";
import bag_component from "../../component/bag_component";
import { ItemType } from "../../shared/face/enums";

/**
 * RPG客户端处理器 - 负责所有客户端交互逻辑
 * 分离UI和业务逻辑
 */
export class RPGClientHandler {
    private rpgComponent: rpg_component;
    
    constructor(rpgComponent: rpg_component) {
        this.rpgComponent = rpgComponent;
    }

    /**
     * 显示技能列表
     */
    showSkillList(): void {
        this.rpgComponent.reload_skills();
        let card = sdk.tool.card.create();
        card.title('我的技能');
        
        if (this.rpgComponent.selfSkill.length == 0) {
            card.l('🚫自身无技能');
        } else {
            for (let i = 0; i < this.rpgComponent.selfSkill.length; i++) {
                let skill = this.rpgComponent.selfSkill[i];
                let skillData = SkillManager.getSkillById(skill.skillId) as Skill;
                // 优先使用 desc 字段，其次使用 reName，最后使用默认名称
                const displayName = skill.reName || skillData.name;
                card.l(`[${i + 1}]Lv.${skill.level} ${displayName}`);
            }
        }
        
        for (let i = 0; i < this.rpgComponent._equipSkills.length; i++) {
            let skill = this.rpgComponent._equipSkills[i];
            let skillData = SkillManager.getSkillById(skill.skillId) as Skill;
            // 优先使用 desc 字段，其次使用 reName，最后使用默认名称
            const displayName = skill.reName || skillData.name;
            card.l(`[${i + this.rpgComponent.selfSkill.length + 1}](装备)${displayName}`);
        }
        
        const buttonConfigs = [
            { text: '查看', action: this.lookSkill.bind(this), mathType: mathType.开头匹配 },
            { text: '遗忘', action: this.forgetSkill.bind(this), mathType: mathType.开头匹配 }
        ];
        
        card.registerButtonIntents(buttonConfigs, this.rpgComponent);
        this.rpgComponent.client_text(card.getText());
    }
    /**
     * 玩家主动复活
     * 1.复活扣除复活币
     * 2.复活后恢复满血
     * 3.如果复活币 不足 那么 扣除50%当前等级经验
     */
    client_reLive():void{
        if(this.rpgComponent.level < 10){
            this.rpgComponent.reLive();
            this.rpgComponent.client_text('复活成功,等级不足10级无消耗');
            return;
        }
        // 1 检查是否有复活币
        let com_prop = this.rpgComponent.getComponent(ComType.背包) as bag_component;
        let prop = com_prop.order_confirm([{key:道具枚举.复活币,val:1,type:ItemType.道具}]);
        if(prop){
            // 无损复活
            this.rpgComponent.reLive();
            this.rpgComponent.client_text('无损复活成功');
        }else{
            // 扣除50%当前等级经验
            let exp = this.rpgComponent.exp.max * 0.5;
            this.rpgComponent.addExp(-exp);
            // 复活后恢复满血
            this.rpgComponent.reLive();
            this.rpgComponent.client_text(`复活成功,扣除${exp}经验`);
        }

    }
    /**
     * 查看指定技能
     */
    lookSkill(data: analysisIntent): void {
        let id = data.Message.content.replace('查看', '');
        if (!id) {
            this.rpgComponent.client_text('技能ID不能为空');
            return;
        }
        let card = sdk.tool.card.create2();
        card.title('技能查看');
        if (!isNaN(Number(id))) {
            let skill = this.rpgComponent.selfSkill[Number(id) - 1];
            if (!skill) {
                skill = this.rpgComponent._equipSkills[Number(id) - 1 - this.rpgComponent.selfSkill.length];
            }
            if (!skill) {
                this.rpgComponent.client_text('未学习此技能,正在搜索技能库..');
                return;
            }
            // 传入施法者对象以获取准确的技能描述
            let _temp = SkillManager.client_data(skill.skillId, card, this.rpgComponent);
            if (!_temp) {
                this.rpgComponent.client_text('技能库中不存在此技能');
                return;
            }
            this.rpgComponent.client_img('panel_common', card.resData);
        } else {
            // 传入施法者对象以获取准确的技能描述
            let _temp = SkillManager.client_data(id, card, this.rpgComponent);
            if (!_temp) {
                this.rpgComponent.client_text('技能库中不存在此技能');
                return;
            }
            this.rpgComponent.client_img('panel_common', card.resData);
        }
    }

    /**
     * 遗忘技能
     */
    forgetSkill(data: analysisIntent): void {
        let index_data = sdk.tool.common.cover_number(data.Message.content);
        if (!index_data.k1) {
            this.rpgComponent.client_text('技能遗忘:遗忘+ID');
            return;
        }
        let skill = this.rpgComponent.selfSkill[index_data.k1 - 1];
        if (!skill) {
            this.rpgComponent.client_text('技能不存在');
            return;
        }
        if (gameCfg.defaultSkill.includes(skill.skillId)) {
            this.rpgComponent.client_text('默认技能无法移除.');
            return;
        }
        this.rpgComponent.selfSkill.splice(index_data.k1 - 1, 1);
        this.rpgComponent.reload_skills();
        this.rpgComponent.client_text('技能遗忘成功');
    }

    /**
     * 显示属性详情
     */
    showAttributes(data: any, title?: string): void {
        this.rpgComponent.fighting_update();
        let baseCom = this.rpgComponent.getComponent(ComType.base) as base_component;
        let tmp = {
            title: title || `宿主档案`,
            show: baseCom.show,
            // 战力
            power: this.rpgComponent._fighting,
            // 唯一ID
            id: this.rpgComponent.id,
            // 昵称
            nickName: baseCom.nickName,
            // 等级
            level: this.rpgComponent.level,
            // 属性
            attributes: [] as { key: Attribute_base; val: number; max: number; Percents: boolean }[],
            // 生命
            hp: [this.rpgComponent.hp_now, this.rpgComponent.getAttribute(Attribute_base.最大生命值)],
            exp: [this.rpgComponent.exp.now, this.rpgComponent.exp.max],
            talent: [] as string[]
        };
        
        let base_attr = [
            [Attribute_base.物理攻击, this.rpgComponent.getAttribute(Attribute_base.物理攻击) + this.rpgComponent.getAttribute(Attribute_base.物理防御)],
            [Attribute_base.物理防御, this.rpgComponent.getAttribute(Attribute_base.物理攻击) + this.rpgComponent.getAttribute(Attribute_base.物理防御)],
            [Attribute_base.魔法攻击, this.rpgComponent.getAttribute(Attribute_base.魔法攻击) + this.rpgComponent.getAttribute(Attribute_base.魔法防御)],
            [Attribute_base.魔法防御, this.rpgComponent.getAttribute(Attribute_base.魔法攻击) + this.rpgComponent.getAttribute(Attribute_base.魔法防御)],
            [Attribute_base.技能缩减, 100],
            [Attribute_base.闪避率, 100],
            [Attribute_base.物理穿透, 100],
            [Attribute_base.魔法穿透, 100],
            [Attribute_base.物理暴击率, 100],
            [Attribute_base.魔法暴击率, 100],
        ];
        
        let Percents = [Attribute_base.技能缩减, Attribute_base.闪避率, Attribute_base.物理暴击率, Attribute_base.魔法暴击率, Attribute_base.物理穿透, Attribute_base.魔法穿透];
        base_attr.forEach(attr => {
            let key = attr[0] as Attribute_base;
            let val = attr[1] as number;
            tmp.attributes.push({
                key: key,
                val: this.rpgComponent.getAttribute(key),
                max: val,
                Percents: Percents.includes(key)
            });
        });
        
        let talent_com = this.rpgComponent.getComponent(ComType.血统) as talent_component;
        tmp.talent = talent_com.getTalentNames();
        data.player.client_img('body', tmp);
    }

    /**
     * 显示战力变化
     */
    showPowerChange(): void {
        let last = this.rpgComponent._fighting;
        this.rpgComponent.fighting_update();
        let change = this.rpgComponent._fighting - last;
        if (change != 0) {
            this.rpgComponent.client_text(`🔥战力变化(${(this.rpgComponent.getComponent(ComType.base) as any).nickName}):${this.rpgComponent._fighting}(${change > 0 ? '🔺' : '🔻'}${change})`);
        }
    }

    /**
     * 显示等级提升
     */
    showLevelUp(level?: number): void {
        let name = this.rpgComponent.getComponent(ComType.base).nickName;
        let emoji = this.rpgComponent.getComponent(ComType.base).emoji;
        const displayLevel = level !== undefined ? level : this.rpgComponent.level;
        this.rpgComponent.client_text(`🔥等级提升(${emoji}${name}):${displayLevel}`);
    }

    showLevelDown():void{
        let name = this.rpgComponent.getComponent(ComType.base).nickName;
        let emoji =this.rpgComponent.getComponent(ComType.base).emoji;
        this.rpgComponent.client_text(`💥等级下降(${emoji}${name}):${this.rpgComponent.level}`);
    }
 

    /**
     * 显示技能学习成功
     */
    showSkillLearned(): void {
        this.rpgComponent.client_text(`技能学习成功`);
    }
} 